package handlers

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"xiao-hong-shu-app/models"
	"xiao-hong-shu-app/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	var arr models.User
	err := models.DB.Where("username=?", username).First(&arr).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if pkg.Md5(password) != arr.Password {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码不正确",
		})
		return
	}
	token := pkg.TokenHandler(strconv.Itoa(int(arr.ID)))
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "登录成功",
		"token": token,
	})
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "2"))
	offset := (page - 1) * pageSize
	var total int64
	models.DB.Model(&models.TextImg{}).Count(&total)
	var arr []models.TextImg
	err := models.DB.Offset(offset).Limit(pageSize).Find(&arr).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"list":  arr,
		"total": total,
	})
}
